<template>
  <div class="app-container">
    <div style="position: absolute;right: 15px;z-index: 1">
      <template v-if="opt == '请验'">
        <el-button class="pan-btn success-btn" @click="send" icon="el-icon-s-promotion" style="float: right;" type="success" size="mini">
          发送
        </el-button>
      </template>
      <template v-if="opt == '修改'">
        <el-button class="pan-btn success-btn" @click="send" icon="el-icon-s-promotion" style="float: right;" type="success" size="mini">
          重新发送
        </el-button>
        <el-button class="pan-btn danger-btn" @click="cancel" icon="el-icon-s-promotion" style="float: right;" type="danger" size="mini">
          作废
        </el-button>
      </template>
      <template v-if="opt == '审核'">
        <el-button class="pan-btn success-btn" @click="auditPass" icon="el-icon-check" style="float: right;" type="success" size="mini">
          审核通过
        </el-button>
        <el-button class="pan-btn danger-btn" @click="auditRefuse" icon="el-icon-close" style="float: right;" type="danger" size="mini">
          退回
        </el-button>
      </template>
      <template v-if="opt == '填写'">
        <el-button class="pan-btn success-btn" @click="saveAll" icon="el-icon-finished" style="float: right;" type="success" size="mini">
          全部保存
        </el-button>
      </template>
    </div>
    <el-tabs tab-position="left">
      <template v-for="(obj, objIndex) in envObjects">
        <el-tab-pane :key="objIndex" :label="obj.envGetObjectName">
          <el-tabs tab-position="top">
            <template v-for="(env, envIndex) in obj.envLists">
              <el-tab-pane :key="envIndex" :label="opt == '填写' ? (env.envGetFrequencyName+(env.status == 3 ? '（已完成）' : '（未完成）')) : env.envGetFrequencyName">
                <el-row :gutter="8">
                  <el-col :xs="24" :sm="24" :md="24" :lg="8" :xl="8">
                    <el-card>
                      <el-form label-position="left" label-width="100px" size="small">
                        <el-form-item label="文件编号:">
                          <span v-html="env.recordNum+'-'+env.versionNum" />
                        </el-form-item>
                        <el-form-item label="培养基批号:">
                          <el-input v-if="sendOrUpdateShow" v-model="env.cultureMediumBatchs" @change="copyToAll(objIndex,envIndex,'cultureMediumBatchs')" />
                          <span v-else v-html="env.cultureMediumBatchs" />
                        </el-form-item>
                        <el-form-item label="产品品规:">
                          <el-select
                            v-if="sendOrUpdateShow"
                            v-model="env.products"
                            :ref="'productSelect-' + objIndex + '-' + envIndex"
                            multiple
                            filterable
                            remote
                            reserve-keyword
                            placeholder=""
                            @focus="setProduct(objIndex,envIndex)"
                            :remote-method="getProduts"
                            :loading="searchProdutLoading"
                            value-key="productId"
                            style="width: 100%">
                            <el-option
                              v-for="p in products"
                              :key="p.productId"
                              :label="p.label"
                              :value="p">
                              <span v-html="p.productName + ' ' + p.productSpec" />
                            </el-option>
                          </el-select>
                          <span v-else v-html="env.productNameSpecs" />
                        </el-form-item>
                        <el-form-item label="产品批号:">
                          <el-input v-if="sendOrUpdateShow" v-model="env.productBatchs" @change="copyToAll(objIndex,envIndex,'productBatchs')" />
                          <span v-else v-html="env.productBatchs" />
                        </el-form-item>
                        <el-form-item label="操作人:">
                          <el-input v-if="sendOrUpdateShow" v-model="env.operationUserName" @change="copyToAll(objIndex,envIndex,'operationUserName')" />
                          <span v-else v-html="env.operationUserName" />
                        </el-form-item>
                        <el-form-item label="试验日期:">
                          <el-date-picker
                            v-if="sendOrUpdateShow"
                            v-model="env.testTime"
                            @change="copyToAll(objIndex,envIndex,'testTime')"
                            align="left"
                            type="date"
                            :clearable="false"
                            range-separator="~"
                            style="width: 100%;"
                            format="yyyy 年 MM 月 dd 日"
                            value-format="yyyy-MM-dd HH:mm:ss" />
                          <span v-else>{{ env.testTime | changeTime }}</span>
                        </el-form-item>
                        <el-form-item label="仪器型号:" v-if="showAp(env.envGetObjectName)">
                          <el-input v-if="sendOrUpdateShow" v-model="env.apparatusModel" @change="copyToAll(objIndex,envIndex,'apparatusModel')" />
                          <span v-else v-html="env.apparatusModel" />
                        </el-form-item>
                        <el-form-item label="仪器编号:" v-if="showAp(env.envGetObjectName)">
                          <el-input v-if="sendOrUpdateShow" v-model="env.apparatusNumber" @change="copyToAll(objIndex,envIndex,'apparatusNumber')" />
                          <span v-else v-html="env.apparatusNumber" />
                        </el-form-item>
                        <el-form-item label="备注:">
                          <el-input v-if="sendOrUpdateShow" v-model="env.remark" @change="copyToAll(objIndex,envIndex,'remark')" />
                          <span v-else v-html="env.remark" />
                        </el-form-item>
                        <el-form-item label="培养温度:" v-if="resultWriteShow(env.status)">
                          <el-input v-if="opt == '填写'" v-model="env.cultureT" @change="setCultureT(objIndex,envIndex)">
                            <template slot="suffix">℃</template>
                          </el-input>
                          <span v-else-if="env.cultureT != null" v-html="env.cultureT + '℃'" />
                        </el-form-item>
                        <el-form-item label="培养时间:" v-if="resultWriteShow(env.status)">
                          <el-date-picker
                            v-if="opt == '填写'"
                            v-model="env.cultureDateArr"
                            @change="setCultureTime(objIndex,envIndex)"
                            align="right"
                            type="daterange"
                            :clearable="false"
                            range-separator="~"
                            style="width: 100%;"
                            format="yyyy 年 MM 月 dd 日"
                            value-format="yyyy-MM-dd HH:mm:ss" />
                          <span v-else>{{ env.cultureDateArr | changeTimeArr }}</span>
                        </el-form-item>
                        <el-form-item label="复核人:" v-if="resultWriteShow(env.status)">
                          <el-input v-if="opt == '填写'" v-model="env.recheckUserName" @change="copyToAll(objIndex,envIndex,'recheckUserName')" />
                          <span v-else v-html="env.recheckUserName" />
                        </el-form-item>
                        <el-form-item label="报告日期:" v-if="resultWriteShow(env.status)">
                          <el-date-picker
                            v-if="opt == '填写'"
                            v-model="env.reportTime"
                            @change="copyToAll(objIndex,envIndex,'reportTime')"
                            align="left"
                            type="date"
                            :clearable="false"
                            range-separator="~"
                            style="width: 100%;"
                            format="yyyy 年 MM 月 dd 日"
                            value-format="yyyy-MM-dd HH:mm:ss" />
                          <span v-else>{{ env.reportTime | changeTime }}</span>
                        </el-form-item>
                        <el-form-item label="阴性对照:" v-if="resultWriteShow(env.status)">
                          <el-input v-if="opt == '填写'" v-model="env.negativeContrast" @change="copyToAll(objIndex,envIndex,'negativeContrast')" />
                          <span v-else v-html="env.negativeContrast" />
                        </el-form-item>
                        <el-form-item label="偏差清单:" v-if="resultWriteShow(env.status)">
                          <el-input v-if="opt == '填写'" v-model="env.deviation" @change="copyToAll(objIndex,envIndex,'deviation')" />
                          <span v-else v-html="env.deviation" />
                        </el-form-item>
                        <el-form-item label="确认结论:" v-if="resultWriteShow(env.status)">
                          <el-radio-group v-if="opt == '填写'" @change="changeEnvComplies(objIndex,envIndex)" v-model="env.isComplies">
                            <el-radio :label="0">符合规定</el-radio>
                            <el-radio :label="1">不符合规定</el-radio>
                          </el-radio-group>
                          <span v-else-if="env.isComplies != null">{{ env.isComplies == 0 ? '符合规定' : '不符合规定' }}</span>
                        </el-form-item>
                      </el-form>
                    </el-card>
                  </el-col>
                  <el-col :xs="24" :sm="24" :md="24" :lg="16" :xl="16">
                    <el-card>
                      <el-table
                        v-if="env.envGetObjectName != '个人卫生'"
                      	:data="env.envItems"
                        v-loading="env.envItemLoading"
                      	border
                        fit
                        highlight-current-row
                        :ref="'items'+objIndex+envIndex"
                        style="width: 100%">
                        <el-table-column
                          v-if="sendOrUpdateShow"
                          type="selection"
                          header-align="center"
                          align="center"
                          width="50">
                        </el-table-column>
                        <el-table-column
                          prop="roomName"
                          header-align="center"
                          align="center"
                          label="房间名称">
                          <template slot-scope="{row}">
                            <el-input v-if="row.edit" v-model="row.roomName" size="small" />
                            <span v-else>{{ row.roomName }}</span>
                          </template>
                        </el-table-column>
                        <el-table-column
                          prop="roomNum"
                          header-align="center"
                          align="center"
                          label="房间编号"
                      		width="150">
                          <template slot-scope="{row}">
                            <el-input v-if="row.edit" v-model="row.roomNum" size="small" />
                            <span v-else>{{ row.roomNum }}</span>
                          </template>
                        </el-table-column>
                        <el-table-column
                          prop="envGetLevelName"
                          header-align="center"
                          align="center"
                          label="洁净级别"
                          width="150">
                          <template slot-scope="scope">
                            <el-select v-if="scope.row.edit" size="small" @change="setEnvGetLevel(objIndex,envIndex,scope.$index)" v-model="scope.row.envGetLevelId" filterable placeholder="">
                              <el-option
                                v-for="item in env.envGetLevelList"
                                :key="item.envGetLevelId"
                                :label="item.envGetLevelName"
                                :value="item.envGetLevelId">
                              </el-option>
                            </el-select>
                            <span v-else>{{ scope.row.envGetLevelName }}</span>
                          </template>
                        </el-table-column>
                        <el-table-column
                          prop="getName"
                          header-align="center"
                          align="center"
                          label="取样位置"
                          width="150">
                          <template slot-scope="{row}">
                            <el-input v-if="row.edit" v-model="row.getName" size="small" />
                            <span v-else>{{ row.getName }}</span>
                          </template>
                        </el-table-column>
                        <el-table-column
                          v-if="sendOrUpdateShow"
                          header-align="center"
                          align="center"
                          label="操作"
                          width="80">
                          <template slot-scope="scope">
                            <el-row>
                              <template v-if="scope.row.edit">
                                <el-col :span="12">
                                  <el-button type="text" @click="addItmeOk(objIndex,envIndex,scope.$index)">
                                    <i class="el-icon-check" />
                                  </el-button>
                                </el-col>
                                <el-col :span="12">
                                  <el-button type="text" @click="subItme(objIndex,envIndex,scope.$index)">
                                    <i class="el-icon-close" />
                                  </el-button>
                                </el-col>
                              </template>
                              <template v-else>
                                <el-col :span="12">
                                  <el-button type="text" @click="addItem(objIndex,envIndex,scope.$index)">
                                    <i class="el-icon-plus" />
                                  </el-button>
                                </el-col>
                                <el-col :span="12">
                                  <el-button type="text" @click="subItme(objIndex,envIndex,scope.$index)">
                                    <i class="el-icon-minus" />
                                  </el-button>
                                </el-col>
                              </template>
                            </el-row>
                          </template>
                        </el-table-column>
                        <el-table-column
                          v-if="resultWriteShow(env.status)"
                          prop="result"
                          header-align="center"
                          align="center"
                          width="150">
                          <template slot="header" slot-scope="scope">
                            菌落数</br>(CFU/皿)
                          </template>
                          <template slot-scope="{row}">
                            <el-input v-if="opt == '填写'" v-model="row.result" size="small" />
                            <span v-else>{{ row.result }}</span>
                          </template>
                        </el-table-column>
                        <el-table-column
                          v-if="resultWriteShow(env.status) && env.envGetObjectName == '浮游菌'"
                          prop="resultComputed"
                          header-align="center"
                          align="center"
                          width="150">
                          <template slot="header" slot-scope="scope">
                            结果</br>(CFU/m³)
                          </template>
                          <template slot-scope="{row}">
                            <el-input v-if="opt == '填写'" v-model="row.resultComputed" size="small" />
                            <span v-else>{{ row.resultComputed }}</span>
                          </template>
                        </el-table-column>
                        <el-table-column
                          v-if="resultWriteShow(env.status)"
                          header-align="center"
                          align="center">
                          <template slot="header" slot-scope="scope">
                            结论</br>符合规定
                          </template>
                          <el-table-column
                            prop="isComplies"
                            header-align="center"
                            align="center"
                            width="150">
                            <template slot="header" slot-scope="scope">
                              <el-radio-group :disabled="opt != '填写'" @change="changeAllItemComplies(objIndex,envIndex)" v-model="env.allItemComplies">
                                <el-radio :label="0">是</el-radio>
                                <el-radio :label="1">否</el-radio>
                              </el-radio-group>
                            </template>
                            <template slot-scope="scope">
                              <el-radio-group v-if="opt == '填写'" @change="changeItemComplies(objIndex,envIndex,scope.$index)" v-model="scope.row.isComplies" size="small">
                                <el-radio :label="0">是</el-radio>
                                <el-radio :label="1">否</el-radio>
                              </el-radio-group>
                              <span v-else>{{ scope.row.isComplies == 0 ? '是' : '否' }}</span>
                            </template>
                          </el-table-column>
                        </el-table-column>
                      </el-table>
                      <div v-else>
                        <el-card>
                          <div slot="header" v-if="!resultWriteShow(env.status)">
                            <el-row>
                              <el-col :span="12">
                                <el-form size="small" label-position="left" label-width="100px">
                                  <el-form-item
                                    v-for="(p,pIndex) in env.persons"
                                    :label="'被测试人 '+(pIndex+1) + ':'"
                                    :key="pIndex">
                                    <template v-if="sendOrUpdateShow">
                                      <el-input v-model="p.name" style="width: 50%" />
                                      <el-button type="danger" class="pan-btn danger-btn" @click.prevent="subPerson(objIndex,envIndex,pIndex)">删除</el-button>
                                    </template>
                                    <template v-else>
                                      {{ p.name }}
                                    </template>
                                  </el-form-item>
                                  <el-form-item v-if="sendOrUpdateShow">
                                    <el-button type="primary" class="pan-btn primary-btn" @click="addPerson(objIndex,envIndex)">增加</el-button>
                                  </el-form-item>
                                </el-form>
                              </el-col>
                            </el-row>
                          </div>
                          <el-table
                            :data="env.envItems"
                            v-loading="env.envItemLoading"
                            border
                            fit
                            highlight-current-row
                            :ref="'items'+objIndex+envIndex"
                            style="width: 100%">
                            <el-table-column
                              v-if="sendOrUpdateShow"
                              type="selection"
                              header-align="center"
                              align="center"
                              width="50">
                            </el-table-column>
                            <el-table-column
                              v-if="resultWriteShow(env.status)"
                              prop="testee"
                              header-align="center"
                              align="center"
                              label="被测试人">
                            </el-table-column>
                            <el-table-column
                              prop="envGetLevelName"
                              header-align="center"
                              align="center"
                              label="洁净级别">
                              <template slot-scope="scope">
                                <el-select v-if="scope.row.edit" size="small" @change="setEnvGetLevel(objIndex,envIndex,scope.$index)" v-model="scope.row.envGetLevelId" filterable placeholder="">
                                  <el-option
                                    v-for="item in env.envGetLevelList"
                                    :key="item.envGetLevelId"
                                    :label="item.envGetLevelName"
                                    :value="item.envGetLevelId">
                                  </el-option>
                                </el-select>
                                <span v-else>{{ scope.row.envGetLevelName }}</span>
                              </template>
                            </el-table-column>
                            <el-table-column
                              prop="getName"
                              header-align="center"
                              align="center"
                              label="测试项目">
                              <template slot-scope="{row}">
                                <el-input v-if="row.edit" v-model="row.getName" size="small" />
                                <span v-else>{{ row.getName }}</span>
                              </template>
                            </el-table-column>
                            <el-table-column
                              v-if="sendOrUpdateShow"
                              header-align="center"
                              align="center"
                              label="操作"
                              width="80">
                              <template slot-scope="scope">
                                <el-row>
                                  <template v-if="scope.row.edit">
                                    <el-col :span="12">
                                      <el-button type="text" @click="addItmeOk(objIndex,envIndex,scope.$index)">
                                        <i class="el-icon-check" />
                                      </el-button>
                                    </el-col>
                                    <el-col :span="12">
                                      <el-button type="text" @click="subItme(objIndex,envIndex,scope.$index)">
                                        <i class="el-icon-close" />
                                      </el-button>
                                    </el-col>
                                  </template>
                                  <template v-else>
                                    <el-col :span="12">
                                      <el-button type="text" @click="addItem(objIndex,envIndex,scope.$index)">
                                        <i class="el-icon-plus" />
                                      </el-button>
                                    </el-col>
                                    <el-col :span="12">
                                      <el-button type="text" @click="subItme(objIndex,envIndex,scope.$index)">
                                        <i class="el-icon-minus" />
                                      </el-button>
                                    </el-col>
                                  </template>
                                </el-row>
                              </template>
                            </el-table-column>
                            <el-table-column
                              v-if="resultWriteShow(env.status)"
                              prop="result"
                              header-align="center"
                              align="center"
                              width="150">
                              <template slot="header" slot-scope="scope">
                                菌落数</br>(CFU/皿)
                              </template>
                              <template slot-scope="{row}">
                                <el-input v-if="opt == '填写'" v-model="row.result" size="small" />
                                <span v-else>{{ row.result }}</span>
                              </template>
                            </el-table-column>
                            <el-table-column
                              v-if="resultWriteShow(env.status)"
                              header-align="center"
                              align="center">
                              <template slot="header" slot-scope="scope">
                                结论</br>符合规定
                              </template>
                              <el-table-column
                                prop="isComplies"
                                header-align="center"
                                align="center"
                                width="150">
                                <template slot="header" slot-scope="scope">
                                  <el-radio-group :disabled="opt != '填写'" @change="changeAllItemComplies(objIndex,envIndex)" v-model="env.allItemComplies">
                                    <el-radio :label="0">是</el-radio>
                                    <el-radio :label="1">否</el-radio>
                                  </el-radio-group>
                                </template>
                                <template slot-scope="scope">
                                  <el-radio-group v-if="opt == '填写'" @change="changeItemComplies(objIndex,envIndex,scope.$index)" v-model="scope.row.isComplies" size="small">
                                    <el-radio :label="0">是</el-radio>
                                    <el-radio :label="1">否</el-radio>
                                  </el-radio-group>
                                  <span v-else>{{ scope.row.isComplies == 0 ? '是' : '否' }}</span>
                                </template>
                              </el-table-column>
                            </el-table-column>
                          </el-table>
                        </el-card>
                      </div>
                    </el-card>
                  </el-col>
                </el-row>
              </el-tab-pane>
            </template>
          </el-tabs>
        </el-tab-pane>
      </template>
    </el-tabs>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { isBlank,parseTime } from '@/common/js/utils'
  import { isPositiveNumber } from '@/common/js/validate'
  import { CODE_OK } from '@/common/js/config'
  import { getProductList } from "@/api/product"
  import { getEnvGetListByParams,getEnvGetLevelList } from "@/api/workshop"
  import { sendEnv,getEnvInfo,returnEnv,auditPass,saveEnvWrite,cancelEnv } from "@/api/env"
  export default {
    name: 'registcheck800',
    data() {
      return {
        opt: null,
        searchProdutLoading: false,
        products: [],
        envObjects: {}
      }
    },
    computed: {
      //只有浮游菌才显示仪器
      showAp(n) {
        return (n) => {return n == '浮游菌'}
      },
      sendOrUpdateShow() {
        return this.opt == '请验' || this.opt == '修改'
      },
      resultWriteShow(s) {
        return (s) => {return s >= 2}
      },
      ...mapGetters([
         'userInfo'
      ])
    },
    created() {
      // this.findActive()
      this.init()
    },
    methods: {
      saveAll() {
        let saveArr = []
        let msgArr = []
        let envListIds = []
        for (let i=0,i2=this.envObjects.length; i<i2; i++) {
          for (let j=0,j2=this.envObjects[i].envLists.length; j<j2; j++) {
            let e = JSON.parse(JSON.stringify(this.envObjects[i].envLists[j]))
            if (e.isUpdated) {
              saveArr.push(JSON.parse(JSON.stringify(e)))
              if (typeof e.isComplies !== 'number') {
                msgArr.push(e.envGetObjectName + '(' + e.envGetFrequencyName + ')')
              }else{
                envListIds.push(e.envListId)
              }
            }
          }
        }
        if (saveArr.length == 0) {
          this.$message.error('没有可保存的内容，请填写后再保存')
          return
        }
        saveEnvWrite(saveArr).then(res => {
          if (res.code === CODE_OK) {
            this.$message.success('保存成功')
            if (msgArr.length > 0) {
              setTimeout(() => {
                this.$message({
                  message: '注意：'+msgArr.join('、')+'请注意填写结论',
                  type: 'warning',
                  duration: 3500
                })
              },200)
            }
            this.$router.push({
              name: "环境监测"
            })
          }else{
            this.$message.error(res.msg)
          }
        })
      },
      changeEnvComplies(i,j) {
        let env = JSON.parse(JSON.stringify(this.envObjects[i].envLists[j]))
        let tempValue = JSON.parse(JSON.stringify(env.isComplies))
        this.envObjects[i].envLists[j].isComplies = null
        if (isBlank(env.cultureT)) {
          this.$message.error('请先填写培养温度后再下总结论')
          return
        } else if(isBlank(env.cultureStartTime) || isBlank(env.cultureEndTime)) {
          this.$message.error('请先填写培养时间后再下总结论')
          return
        }else if(isBlank(env.recheckUserName)) {
          this.$message.error('请先填写复核人后再下总结论')
          return
        }else if(isBlank(env.reportTime)) {
          this.$message.error('请先填写报告日期后再下总结论')
          return
        }
        for (let m=0,n=env.envItems.length; m<n; m++) {
          if (typeof env.envItems[m].isComplies !== 'number') {
            this.$message.error('请先对每个位置结论后再下总结论')
            return
          }else if(isBlank(env.envItems[m].result)) {
            this.$message.error('请先对每个位置填写菌落数后再下总结论')
            return
          }
        }
        this.envObjects[i].envLists[j].isComplies = tempValue
        this.envObjects[i].envLists[j].isUpdated = true
      },
      changeAllItemComplies(i,j) {
        let c = this.envObjects[i].envLists[j].allItemComplies
        for (let m=0,n=this.envObjects[i].envLists[j].envItems.length; m<n; m++) {
          this.envObjects[i].envLists[j].envItems[m].isComplies = c
          this.changeItemComplies(i,j,m)
        }
      },
      changeItemComplies(i,j,rowIndex) {
        if (isBlank(this.envObjects[i].envLists[j].envItems[rowIndex].result)
          || (this.envObjects[i].envGetObjectName == '浮游菌' && isBlank(this.envObjects[i].envLists[j].envItems[rowIndex].resultComputed))) {
          this.$message.error('请先填写菌落数后再下结论,若是浮游菌请先填写结果')
          this.envObjects[i].envLists[j].envItems[rowIndex].isComplies = null
        }
      },
      init() {
        this.opt = this.$route.params.opt
        switch (this.opt){
          case '查看':
            this.lookInit()
            break
          case '请验':
            this.sendInit()
            break
          case '修改':
            this.updateInit()
            break
          case '审核':
            this.auditInit()
            break
          case '填写':
            this.writeInit()
            break
          default:
            this.$message.error('未选择任何操作，请重新选择所要进行的操作')
            this.$router.push({
              name: "环境监测"
            })
        }
      },
      lookInit() {
        const params = {
          envMergeId: this.$route.params.info.envMergeId
        }
        getEnvInfo(params).then(res => {
          if (res.code === CODE_OK) {
            this.envObjects = res.envObjects
            this.pushProducts()
            this.grwsFlushItems()
          }else{
            this.$message.error(res.msg)
          }
        })
      },
      sendInit() {
        if (this.$route.params.info.envObjects == undefined) {
          this.$message.error('请重新发起')
          window.history.go(-1)
          return
        }
        let now = parseTime(new Date())
        this.envObjects = this.$route.params.info.envObjects.map(obj => {
          obj.envLists = obj.envLists.map(env => {
            this.$set(env,'operationUserName',this.userInfo.name)
            this.$set(env,'testTime',now)
            this.$set(env,'envItems',[])
            this.$set(env,'envItemLoading',true)
            return env
          })
          return obj
        })
        this.getInfoForItems()
      },
      updateInit() {
        const params = {
          envMergeId: this.$route.params.info.envMergeId
        }
        getEnvInfo(params).then(res => {
          if (res.code === CODE_OK) {
            this.envObjects = res.envObjects
            this.pushProducts()
            this.grwsFlushItems()
            this.getInfoForItems()
          }else{
            this.$message.error(res.msg)
          }
        })
      },
      auditInit() {
        const params = {
          envMergeId: this.$route.params.info.envMergeId
        }
        getEnvInfo(params).then(res => {
          if (res.code === CODE_OK) {
            this.envObjects = res.envObjects
            this.pushProducts()
            this.grwsFlushItems()
          }else{
            this.$message.error(res.msg)
          }
        })
      },
      writeInit() {
        const params = {
          envMergeId: this.$route.params.info.envMergeId
        }
        getEnvInfo(params).then(res => {
          if (res.code === CODE_OK) {
            this.envObjects = res.envObjects.map(o => {
              o.envLists = o.envLists.map(e => {
                this.$set(e,'allItemComplies','')
                this.$set(e,'isUpdated',false)
                if (!isBlank(e.cultureStartTime) && !isBlank(e.cultureEndTime)) {
                  this.$set(e,'cultureDateArr',[e.cultureStartTime,e.cultureEndTime])
                }
                e.envItems = e.envItems.map(it => {
                  if (isBlank(it.result)) {
                    it.result = '0'
                    if (e.envGetObjectName == '浮游菌') {
                      it.resultComputed = '0'
                    }
                  }
                  return it
                })
                return e
              })
              return o
            })
            this.pushProducts()
          }else{
            this.$message.error(res.msg)
          }
        })
      },
      pushProducts() {
        for (let i=0,j=this.envObjects.length; i<j; i++) {
          for (let m=0,n=this.envObjects[i].envLists.length; m<n; m++) {
            if (!isBlank(this.envObjects[i].envLists[m].products)) {
              for (let x=0,y=this.envObjects[i].envLists[m].products.length; x<y; x++) {
                let p = JSON.parse(JSON.stringify(this.envObjects[i].envLists[m].products[x]))
                this.$set(p,'label',p.productName + ' ' + p.productGmp)
                this.envObjects[i].envLists[m].products[x] = JSON.parse(JSON.stringify(p))
                if (this.products.findIndex(p2 => p2.productId == p.productId) == -1) {
                  this.products.push(JSON.parse(JSON.stringify(p)))
                }
              }
            }
          }
        }
      },
      grwsFlushItems() {
        for (let i=0,j=this.envObjects.length; i<j; i++) {
          if (this.envObjects[i].envGetObjectName == '个人卫生') {
            for (let x=0,y=this.envObjects[i].envLists.length; x<y; x++) {
              let persons = []
              let envItems = []
              for (let m=0,n=this.envObjects[i].envLists[x].envItems.length; m<n; m++) {
                let item = JSON.parse(JSON.stringify(this.envObjects[i].envLists[x].envItems[m]))
                if (persons.findIndex(p => p.name == item.testee) == -1) {
                  persons.push({
                    name: item.testee
                  })
                }
                if (envItems.findIndex(eit => eit.envGetId == item.envGetId) == -1) {
                  envItems.push(JSON.parse(JSON.stringify(item)))
                }
              }
              this.$set(this.envObjects[i].envLists[x],'persons',JSON.parse(JSON.stringify(persons)))
              this.envObjects[i].envLists[x].envItems = JSON.parse(JSON.stringify(envItems))
            }
          }
        }
      },
      getInfoForItems() {
        for (let i=0,j=this.envObjects.length; i<j; i++) {
          for (let x=0,y=this.envObjects[i].envLists.length; x<y; x++) {
            this.$set(this.envObjects[i].envLists[x],'allItems',[])
            let params = {
              i: i,
              x: x,
              workshopId: this.envObjects[i].envLists[x].workshopId,
              envGetObjectId: this.envObjects[i].envLists[x].envGetObjectId,
              envGetFrequencyId: this.envObjects[i].envLists[x].envGetFrequencyId
            }
            if (isBlank(this.envObjects[i].envLists[x].envItems)) {
              //获取基础点位
              getEnvGetListByParams(params).then(res => {
                if (res.code === CODE_OK) {
                  let resI = parseInt(res.i)
                  let resX = parseInt(res.x)
                  let envItems = res.envGetList
                  if (isBlank(envItems)) {
                    envItems.push({
                      envGetId: null,
                      roomName: null,
                      roomNum: null,
                      envGetLevelId: null,
                      envGetLevelName: null,
                      getName: null,
                      edit: true
                    })
                    this.envObjects[resI].envLists[resX].envItems = envItems
                    this.$message({
                      message: '系统中不存在可选择点位，请向管理员提供基础点位信息，导入系统后，便可选择点位，此时请手动填写点位',
                      type: 'error',
                      duration: 3500
                    })
                  }else{
                    this.envObjects[resI].envLists[resX].envItems = envItems.map(v => {
                      this.$set(v,'edit',false)
                      return v
                    })
                  }
                  if (this.envObjects[resI].envLists[resX].envGetObjectName == '个人卫生') {
                    this.$set(this.envObjects[resI].envLists[resX],'persons',[{
                      name: ''
                    }])
                  }
                  this.envObjects[resI].envLists[resX].envItemLoading = false
                }else{
                	this.$message.error(res.msg)
                }
              })
            }
            getEnvGetLevelList(params).then(res => {
              if (res.code === CODE_OK) {
                let resI = parseInt(res.i)
                let resX = parseInt(res.x)
                this.$set(this.envObjects[resI].envLists[resX],'envGetLevelList',res.envGetLevelList)
              }else{
                this.$message.error(res.msg)
              }
            })
          }
        }
      },
      copyToAll(i,j,prop) {
        this.envObjects[i].envLists[j].isUpdated = true
        //只允许第一单正向覆盖
        if (this.envObjects.length == 1 && this.envObjects[0].envLists.length == 1) {
          return
        }
        if (i == 0 && j == 0) {
          let value = this.envObjects[i].envLists[j][prop]
          if (!isBlank(value)) {
            this.$confirm('是否复制到全部?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(async () => {
              let sure = false
              for (let m=0,n=this.envObjects.length; m<n; m++) {
                for (let x=0,y=this.envObjects[m].envLists.length; x<y; x++) {
                  this.$set(this.envObjects[m].envLists[x],prop,value)
                  this.envObjects[m].envLists[x].isUpdated = true
                  if (prop == 'cultureDateArr') {
                    this.$set(this.envObjects[m].envLists[x],'cultureStartTime',value[0])
                    this.$set(this.envObjects[m].envLists[x],'cultureEndTime',value[1])
                  }
                  if (prop == 'products') {
                    this.$set(this.envObjects[m].envLists[x],'productIds',value.map(p => {
                      return p.productId
                    }).join(','))
                    this.$set(this.envObjects[m].envLists[x],'productNameSpecs',value.map(p => {
                      return p.productName + ' ' + p.productSpec
                    }).join(','))
                  }
                }
              }
            }).catch(() => {})
          }
        }
      },
      auditPass() {
        const data = {
          envMergeId: this.envObjects[0].envLists[0].envMergeId
        }
        auditPass(data).then(res => {
          if (res.code === CODE_OK) {
            this.$message.success('提交成功')
            window.history.go(-1)
          }else{
            this.$message.error(res.msg)
          }
        })
      },
      auditRefuse() {
        const data = {
          envMergeId: this.envObjects[0].envLists[0].envMergeId
        }
        returnEnv(data).then(res => {
          if (res.code === CODE_OK) {
            this.$message.success('退回成功')
            window.history.go(-1)
          }else{
            this.$message.error(res.msg)
          }
        })
      },
      send() {
        let envLists = this.formVerifyAndNeatenData()
        if (!isBlank(envLists)) {
          const envMergeList = {
            envMergeId: this.opt == '请验' ? null : envLists[0].envMergeId,
            listCount: envLists.length,
            envLists: envLists
          }
          sendEnv(envMergeList).then(res => {
            if (res.code === CODE_OK) {
              this.$message.success('发送成功')
              window.history.go(-1)
            }else{
              this.$message.error(res.msg)
            }
          })
        }
      },
      formVerifyAndNeatenData() {
        let envLists = []
        for (let i=0,j=this.envObjects.length; i<j; i++) {
          for (let x=0,y=this.envObjects[i].envLists.length; x<y; x++) {
            let el = JSON.parse(JSON.stringify(this.envObjects[i].envLists[x]))
            this.$set(el,'position',i+''+x)
            this.$set(el,'name',this.envObjects[i].envGetObjectName+'【'+this.envObjects[i].envLists[x].envGetFrequencyName+'】')
            envLists.push(el)
          }
        }
        for (let i=0,j=envLists.length; i<j; i++) {
          if (isBlank(envLists[i].cultureMediumBatchs)) {
            this.$message.error(envLists[i].name+':培养基批号不能为空')
            return null
          }
          if (isBlank(envLists[i].operationUserName)) {
            this.$message.error(envLists[i].name+':操作人不能为空')
            return null
          }
          if (isBlank(envLists[i].testTime)) {
            this.$message.error(envLists[i].name+':试验日期不能为空')
            return null
          }
          let selectItems
          if (isBlank((selectItems = JSON.parse(JSON.stringify(this.$refs['items'+envLists[i].position][0].selection))))) {
            this.$message.error(envLists[i].name+':请勾选至少一个要检验的点位')
            return null
          }
          this.$set(envLists[i],'itemCount',selectItems.length)
          for (let x=0,y=selectItems.length; x<y; x++) {
            if (selectItems[x].edit) {
              this.$message.error(envLists[i].name+':请先保存新增的点位')
              return null
            }
            selectItems[x].itemStatus = 1
          }
          if (envLists[i].envGetObjectName == '个人卫生') {
            if (envLists[i].persons.length == 0) {
              this.$message.error(envLists[i].name+'至少需要一个被测试人')
              return null
            }else if(envLists[i].persons.length == 1 && isBlank(envLists[i].persons[0].name)) {
              this.$message.error(envLists[i].name+'至少需要一个被测试人')
              return null
            }else{
              let arr = []
              for (let t1 of selectItems) {
                let t2 = JSON.parse(JSON.stringify(t1))
                for (let p1 of envLists[i].persons) {
                  let p2 = JSON.parse(JSON.stringify(p1))
                  this.$set(t2,'testee',p2.name)
                  arr.push(JSON.parse(JSON.stringify(t2)))
                }
              }
              selectItems = arr
            }
          }
          envLists[i].envItems = selectItems
        }
        return envLists
      },
      cancel() {
        this.$confirm('是否作废?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const envMergeList = {
            envMergeId: this.envObjects[0].envLists[0].envMergeId
          }
          cancelEnv(envMergeList).then(res => {
            if (res.code === CODE_OK) {
              this.$message.success('作废成功')
              window.history.go(-1)
            }else{
              this.$message.error(res.msg)
            }
          })
        }).catch(() => {})
      },
      subPerson(i,j,index) {
        if (this.envObjects[i].envLists[j].persons.length == 1) {
          this.$message.error('至少需要一个被测试人')
          return
        }
        this.envObjects[i].envLists[j].persons.splice(index,1)
      },
      addPerson(i,j) {
        this.envObjects[i].envLists[j].persons.push({
          name: null
        })
      },
      setEnvGetLevel(i,j,index) {
        let id = this.envObjects[i].envLists[j].envItems[index].envGetLevelId
        this.envObjects[i].envLists[j].envItems[index].envGetLevelName = this.envObjects[i].envLists[j].envGetLevelList.find(v => v.envGetLevelId == id).envGetLevelName
      },
      addItmeOk(i,j,index) {
        let row = this.envObjects[i].envLists[j].envItems[index]
        let isPer = this.envObjects[i].envLists[j].envGetObjectName == '个人卫生'
        if (!isPer && isBlank(row.roomName)) {
          this.$message.error('该点位的房间名称不能为空')
          return
        }
        if (!isPer && isBlank(row.roomNum)) {
          this.$message.error('该点位的房间编号不能为空')
          return
        }
        if (isBlank(row.envGetLevelName)) {
          this.$message.error('该点位的洁净级别不能为空')
          return
        }
        if (isBlank(row.getName)) {
          this.$message.error(!isPer ? '该点位的取样位置不能为空' : '测试项目不能为空')
          return
        }
        this.envObjects[i].envLists[j].envItems[index].edit = false
      },
      subItme(i,j,index) {
        if (this.envObjects[i].envLists[j].envItems.length == 1) {
          this.$message.error('至少需要一个点位')
          return
        }
        this.envObjects[i].envLists[j].envItems.splice(index,1)
      },
      addItem(i,j,index) {
        let v = JSON.parse(JSON.stringify(this.envObjects[i].envLists[j].envItems[index]))
        v.envItemId = null
        v.envGetId = null
        v.getName = null
        v.edit = true
        this.envObjects[i].envLists[j].envItems.splice(index+1,0,v)
      },
      setCultureTime(i,j) {
        this.envObjects[i].envLists[j].cultureStartTime = this.envObjects[i].envLists[j].cultureDateArr[0]
        this.envObjects[i].envLists[j].cultureEndTime = this.envObjects[i].envLists[j].cultureDateArr[1]
        this.copyToAll(i,j,'cultureDateArr')
      },
      setCultureT(i,j) {
        if (!isPositiveNumber(this.envObjects[i].envLists[j].cultureT)) {
          this.$message.error('温度为正数')
          this.envObjects[i].envLists[j].cultureT = null
          return
        }
        this.copyToAll(i,j,'cultureT')
      },
      setProduct(i,j) {
        this.$refs['productSelect-'+i+'-'+j][0].$refs.input.blur = () => {
          let ps = this.envObjects[i].envLists[j].products
          this.envObjects[i].envLists[j].productIds = ps.map(p => {
            return p.productId
          }).join(',')
          this.envObjects[i].envLists[j].productNameSpecs = ps.map(p => {
            return p.productName + ' ' + p.productSpec
          }).join(',')
          this.copyToAll(i,j,'products')
        }
      },
      getProduts(name) {
        if (name != '') {
          this.searchProdutLoading = true
          const params = {
            page: 1,
            limit: 10,
            productName: name,
            productCategoryId: 5
          }
          getProductList(params).then(res => {
          	if (res.code === CODE_OK) {
              let ps = res.page.list.map(v => {
                this.$set(v,'label',v.productName + ' ' + v.productGmp)
                return v
              })
              this.products.unshift(...ps)
          	}else{
          		this.$message.error(res.msg)
          	}
            this.searchProdutLoading = false
          })
        }
      }
    }
  }
</script>

<style scoped>
  >>> .el-col>.el-button{
    padding: 0;
  }
</style>
